const ora = require("ora");
const { boolChoies } = require("../config");
const inquirer = require("inquirer");
const t = require("../config/dict");
const config = require("../mfo.config.js");
const {
  exeCommandSpawn,
  log,
  isWindows,
  packageManager,
} = require("../lib/utils");
const path = require("path");

const runBuild = (context, _LOCALSOURCE) => {
  let spinner = null;
  spinner = ora(
    [
      t(context.lang, "拉取远程依赖项"),
      ",",
      t(context.lang, "请稍候"),
      " ...",
    ].join(" ")
  );
  spinner.start();

  const execItem = () => {
    return new Promise((resolve, reject) => {
      const cwd = path.resolve(process.cwd(), context.metadata.projectDir);
      packageManager(cwd)
        .install(false, {
          cwd,
          register: _LOCALSOURCE,
        })
        .then(() => {
          spinner &&
            ((spinner.text = [
              t(context.lang, "拉取远程依赖项"),
              ",",
              t(context.lang, "完成") + t(context.lang, "。"),
            ].join(" ")),
            spinner.succeed());
          process.env.DEBUG === "true" &&
            log("success", {
              message: [
                t(context.lang, "拉取远程依赖项"),
                t(context.lang, "完成") + t(context.lang, "。"),
              ].join(" "),
            });
          resolve(context);
        })
        .catch((err) => {
          spinner &&
            ((spinner.text = [
              t(context.lang, "拉取远程依赖项"),
              t(context.lang, "失败") + t(context.lang, "。"),
            ].join(" ")),
            spinner.fail());
          process.env.DEBUG === "true" &&
            log("error", {
              message: err,
            });
          resolve(context);
        });
    });
  };
  return execItem(0);
};

module.exports = (context) => {
  const _LOCALSOURCE = context.source; //|| process.env.LOCALSOURCE || config.LOCALSOURCE;
  const type = context.metadata.projectType[0].toLowerCase();
  if (
    /uniapp\(vue[0-9]+,\s*(vite|webpack),\s*/.test(type) ||
    !/uniapp/.test(type)
  ) {
    if (
      context.metadata.projectMode &&
      context.metadata.projectMode === "auto"
    ) {
      context.metadata.projectBuild = "yes";
      return runBuild(context, _LOCALSOURCE);
    }
    return inquirer
      .prompt([
        {
          name: "projectBuild",
          message: t(context.lang, "安装依赖项") + "?",
          default: "yes",
          pageSize: 3,
          type: "rawlist",
          choices: [...t(context.lang, boolChoies)],
        },
      ])
      .then((answers) => {
        context.metadata.projectBuild = answers.projectBuild;
        if (answers.projectBuild === "yes") {
          return runBuild(context, _LOCALSOURCE);
        } else {
          return context;
        }
      });
  } else {
    log("warn", {
      message:
        t(context.lang, "提示") +
        ": " +
        t(context.lang, "不构建") +
        " " +
        context.name +
        t(context.lang, "。"),
    });
    return context;
  }
};
